package zhieasy.cn.xpu_helper.controller.common;

import io.swagger.annotations.*;
import javafx.geometry.Pos;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import zhieasy.cn.common.utils.ResultVOUtil;
import zhieasy.cn.common.utils.result.ResultUtils;
import zhieasy.cn.common.vo.ResultVO;
import zhieasy.cn.model.common.WechatUser;
import zhieasy.cn.service.common.WechatUserService;
import zhieasy.cn.xpu_helper.security.utils.JwtUtils;

import javax.servlet.http.HttpSession;

/**
 * @author DaHang
 * @date 2020/8/14 23:31
 */
@Api(tags = "common模块，微信用户类操作接口")
@Slf4j
@RestController
@RequestMapping("/common/wechatUser")
public class WechatUserController {

    @Autowired
    WechatUserService wechatUserService;

    @Autowired
    JwtUtils jwtUtils;

    /**
     * 新增用户
     * @return
     */
    @ApiOperation(
        value = "/common/wechatUser/addUser",
        notes = "新用户第一次调用登录接口后调用该接口，将新用户添加进数据库",httpMethod = "POST")
    @ApiImplicitParam(dataTypeClass = WechatUser.class,value = "用户的各种基本信息",required = true)
    @ApiResponses({
        @ApiResponse(code=700,message="没有访问权限,请联系管理员"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对"),
        @ApiResponse(code=200,message="新增用户成功"),
        @ApiResponse(code=2100,message="用户名已经存在"),
        @ApiResponse(code=2101,message="新增用户失败")
    })
    @RequestMapping(value = "/user" , method = RequestMethod.POST)
    public ResultVO addUser(@RequestBody WechatUser user) {

        user.setWxOpenId(WechatUser.getWechatUserOpenIdFromSecurityContext());
        boolean isSuccess = wechatUserService.insertWechatUser(user);
        if (isSuccess){
            return ResultUtils.success("新增用户成功",jwtUtils.generateToken(user));
        }
        return ResultVOUtil.error(2100,"新增失败");
    }

    /**
     * 编辑用户保存
     * @return
     */
    @ApiOperation(value = "修改用户信息",notes = "修改用户信息")
    @RequestMapping(value = "/user",method = RequestMethod.PUT)
    public ResultVO updateSaveUser(@ApiParam("用户信息实体类")@RequestBody WechatUser user){
        //判断用户是否存在
        WechatUser wechatUser = WechatUser.getWechatUserFromSecurityContext();
        //判断一下是不是给用户
        user.setWxOpenId(wechatUser.getWxOpenId());
        boolean b = wechatUserService.updateById(user);
        if(b){
            return ResultUtils.success("编辑成功");
        }else{
            return ResultUtils.error("编辑失败");
        }
    }

    /**
     * 根据用户id查询用户端
     * @return
     */
    @RequestMapping(value = "/user/{openId}",method = RequestMethod.GET)
    public ResultVO getUserById(@ApiParam("用户id")@PathVariable("openId")String openId){
        WechatUser wechatUser = wechatUserService.getWechatUserByOpenID(openId);
        return ResultUtils.success("查询成功",wechatUser);
    }


}
